<?php

defined('BASEPATH') or die('forbidden');

class Moduledetail_Controller Extends Controller {

	private $moduleList;	//模块列表

	//传给index页面
	private $moduleDetailList;	//模块策略列表
	//private $columnStringList;	//模块策略名相应的名字显示

	//传给添加页面的数据
	private $addModuleDetailList;	//模块策略列表
	//private $addColumnStringList;	//模块策略名相应的名字显示

	function _init() {
		check_level(50, segment(0), segment(1), segment(2, 'index'));
		require_once(CONFIGPATH . 'inc.php');

		//查找当前所有模块
		$selectSql="SELECT * FROM act_module ";
		$this->db->query($selectSql);
		while ($n = $this->db->get_array('default', MYSQL_ASSOC)) {
			$this->moduleList[$n['tableenum']]['tableenum'] = $n['tableenum'];
			$this->moduleList[$n['tableenum']]['des'] = $n['des'];
			$this->moduleList[$n['tableenum']]['tablename'] = $n['tablename'];
		}
		//print_r($this->moduleList);
		$columnString = array();	//模块中相应的string名字
		foreach ($this->moduleList as $key => $value)
		{
			//先获取表中的列名
			$tableColumNameList = $this->db->get_table_column_names($value['tablename']);

			$selectSql="SELECT * FROM  ".$value['tablename'];
			$this->db->query($selectSql);
			if(0 == $this->db->affected_rows())
			{
				echo "<script>alert('" .$value['des']." ". translate('C_CREATE_STRATEGY') . "');</script>";
				return;
			}
			while ($n = $this->db->get_array('default', MYSQL_ASSOC))
			{
				//从数据表中的每一个列名选出来
				foreach ($tableColumNameList as $columnName)
				{
					$this->moduleDetailList[$value['tableenum']][$n['strategyid']][$columnName] = $n[$columnName];
						
					$this->addModuleDetailList[$value['tableenum']][$columnName] = $n[$columnName];
					/*
					if($columnName == 'strategyid')
					{
						$this->columnStringList[$value['tableenum']][$columnName] = translate('ACTIVITY_STRATEGY_STRAGEGYID');
					}else if($columnName == 'strategyname')
					{
						$this->columnStringList[$value['tableenum']][$columnName] = translate('ACTIVITY_STRATEGY_STRAGEGYNAME');
					}else
					{
						$strOps = strlen('act_mod_');//表名是此开头的，比如 act_mod_treasurebox
						$this->columnStringList[$value['tableenum']][$columnName] =
						translate(strtoupper("ACTIVITY_".substr($value['tablename'],$strOps)."_".$columnName));
					}
					*/
				}
			}
		}
		//print_r($this->moduleDetailList);
		//print_r($this->columnStringList);
	}

	function index() {

		$this->view->display("activity/moduledetail/index");
	}

	function flexigrid() {
		list($colkey, $colsinfo, $where, $sortname, $sortorder, $offset, $rp, $page) = $this->common->get_flexigrid_params();

		//print_r($colsinfo);

		$rows = array();
		$total = 0;	//总的数据条数
		foreach ($this->moduleDetailList as $tableenum=>$value)
		{
			foreach ($value as $strategyid => $subvalue)
			{
				$data = array();

				$data['id'] = $tableenum."-".$strategyid;
				$data['tablename'] = $this->moduleList[$tableenum]['des'];
				$data['strategyname'] = $subvalue['strategyname'];

				//在此id为tableenum+strategyid
				$id = $tableenum."-".$strategyid;

				$rows[] = array('id' => $id, 'cell' => array_values($data));
				++$total;
			}
		}

		$result = array(
            'page' => $page,
            'total' => $total,
            'rows' => $rows
		);
		echo json_encode($result);

	}

	function add() {

		if (is_submit())
		{
			$rowdata = $_POST['row'];
			//print_r($rowdata);
			//print_r($_POST);
			//echo "id = $id ";

			//先查下是否有此表格
			$sql="select * from act_module where tableenum = '$rowdata[tableenum]'";
			//echo $selectSql;
			$cRow=$this->db->one($sql);
			if(0 == count($cRow))
			{
				echo " sql = $sql ";
				echo "<script>alert('server can not find tableenum $rowdata[tableenum]');</script>";
				return ;
			}
			$tablename = $cRow['tablename'];
			//看下此策略名，是否已经存在
			$sql = "select * from ".$tablename." where strategyname = '$rowdata[strategyname]'";
			$cRow=$this->db->query($sql);
			if(0 < $this->db->affected_rows())
			{
				echo " sql = $sql ";
				echo "<script>alert('stategyname $rowdata[strategyname] has the same, please input again');</script>";
				return ;
			}
				
			//可以插入数据了
			//查找下当前最大的Strategyid
			$strategyid = 1;
			foreach ($this->moduleDetailList[$rowdata['tableenum']] as $key => $value)
			{
				if ($key > $strategyid) {
					$strategyid = $key;
				}
			}
			$strategyid += 1;	//在此基础上加1
				
			//先把tableenum去掉，其它的都可以
			unset($rowdata['tableenum']);
			//unset($rowdata['strategyid']);
			/*
			 $data = array();
			 foreach ($rowdata as $key => $value)
			 {
				$data[$key]=$value;
				}
				$data['strategyid']=$strategyid;
				*/
			$rowdata['strategyid']=$strategyid;
			print_r($rowdata);
			if(false == $this->db->insert($tablename, $rowdata))
			{
				//	echo " insert data fail ";
			}else
			{
				//	echo " success ";
			}
			cp_tips("success");
		}
		$this->view->assign("moduleList",$this->moduleList);
		$this->view->assign('moduleDetailList',$this->addModuleDetailList);
		//$this->view->assign("columnStringList",$this->columnStringList);
		$this->view->display("activity/moduledetail/add");
			
	}

	function edit($id) {
		//$id 格式为 $tableenum."-".$strategyid
		$strArr = explode("-", $id);
		if (2>count($strArr)) {
			error(translate('C_INVALID_PARAM_ID', $tableenum));
			return;
		}

		if(is_submit())
		{
			$rowdata = $_POST['row'];	//数据
			$tablename = $_POST['tablename'];	//表名
			$strategyid = $_POST['strategyid'];	//策略名
			$tableenum = $_POST['tableenum'];	//模块编号
			//print_r($_POST);

			$sendSuccessAreaList = array();	//发送成功的区号
			$sendFailAreaList = array();	//发送失败的区号
				
			//先把数据都插入到数据库中去
			$result = $this->db->update($tablename, $rowdata,array('strategyid'=>$strategyid));
			if(false == $result )
			{
				//print_r($rowdata);
				//echo " tablename:$tablename strategyid:$strategyid update fail...";
				return;		
			}
			//更新下分组策略中的特策略名
			$this->db->update("act_area_strategy", array("strategyname"=>$rowdata['strategyname']),
				array("strategyid"=>$strategyid,"tableenum"=>$tableenum));

			//通知到其它区去
			//action都是52
			$arrHost = array();

			$nowTime = time();	//得到当前的时间
			//找到所有的区网址
			$sql = "select * from act_area_strategy as A, tt_areasample as B
		            		where A.areaid = B.id and endtime > $nowTime 
		            		and tableenum = $tableenum and strategyid = $strategyid ";
			//echo "sql:$sql";
			$this->db->query($sql);
			while ($n = $this->db->get_array('default', MYSQL_ASSOC)) {
				//print_r($n);
				$arrHost[$n['areaid']]['host'] = $n['host'];
				$arrHost[$n['areaid']]['areaname'] = $n['name'];
				$arrHost[$n['areaid']]['des'] = $n['des'];
				$arrHost[$n['areaid']]['starttime'] = $n['starttime'];
				$arrHost[$n['areaid']]['endtime'] = $n['endtime'];
			}
			if(0 == count($arrHost))
			{
				//没有区选择这个策略，就不去修改了
				echo " update success ";
				return;
			}
			//print_r($arrHost);
			//增加json数据
			unset($jsonData);
			$jsonData = array();

			$jsonData['tableenum'] = strval($tableenum);
			$jsonData['tablename'] = strval($tablename);
			$jsonData['strategyid'] = strval($strategyid);
				
			//print_r($jsonData);
			//通知各个区域
			foreach ($arrHost as $subkey => $subvalue)
			{
				$jsonData['des'] = (string)$subvalue['des'];
				$jsonData['starttime'] = (string)$subvalue['starttime'];
				$jsonData['endtime'] = (string)$subvalue['starttime'];

				$jsonArray[] = $jsonData;
				//print_r($jsonData);
				$sendjsonData = json_encode($jsonArray);

				//print_r($value);
				//echo " host:".$value['host'];
				$url = $subvalue['host']."action=52&json_str=".$sendjsonData;
				//echo "url = $url";
				$ret = vpost($url);

				if (0 != $ret) {
					$sendFailAreaList[]['area'] = $subkey;
					$sendFailAreaList[]['areaname'] = $value['areaname'];
					$sendFailAreaList[]['url'] = $url;
					break;
				}else
				{
					//echo "area num:".$subkey." send success ";
					$sendSuccessAreaList[]['area'] = $subkey;
					$sendSuccessAreaList[]['areaname'] = $value['areaname'];
					$sendSuccessAreaList[]['url'] = $url;

				}
			}

			if(0 < count($sendSuccessAreaList))
			{
				echo "send succes area list:";
				foreach ($sendSuccessAreaList as $key => $value)
				{
					echo " ".$value['area'].",";
				}
			}
			if(0 < count($sendFailAreaList))
			{
				echo "send fail area list:";
				foreach ($sendFailAreaList as $key => $value)
				{
					echo " ".$value['area'].",";
				}
			}
			if(0 == count($sendSuccessAreaList) && 0 == count($sendFailAreaList))
			{
				echo " update success ";
			}	
		}else
		{
			$tableenum = $strArr[0];
			$strategyid = $strArr[1];
			//echo " tableenum = $tableenum strategyid = $strategyid ";
				
			//根据表名把数据传过去
			$modulename = $this->moduleList[$tableenum]['des'];
			$tablename = $this->moduleList[$tableenum]['tablename'];
			$displayView = $this->getDisplayView($tablename);
			//echo " displayview = $displayView ";
			$sql = "select * from $tablename where strategyid = $strategyid ";
			$row=$this->db->one($sql);
			//echo " sql = $sql ";
			//print_r($row);
			$this->view->assign("tablename",$tablename);		//传表名过去
			$this->view->assign("modulename",$modulename);		//传模块名过去
			$this->view->assign("tableenum",$tableenum);		//传模块号
			$this->view->display("activity/moduledetail/$displayView", array('row' => $row));	//传数据 过去
		}
		
	}

	function del($id) {
		$strArr = explode("-", $id);
		if (2>count($strArr)) {
			error(translate('C_INVALID_PARAM_ID', $tableenum));
			return;
		}	
		$tableenum = $strArr[0];
		$strategyid = $strArr[1];
		$tablename = $this->moduleList[$tableenum]['tablename'];
		
		$c = 0;
		$r = '';
		//echo " id=$id ";
		if ($this->db->delete($tablename, array('strategyid' => $strategyid))) {
			insert_log(translate('MENU_ACTIVITY_MODULEDETAIL'),translate('DEL'), $autoid);
			$c = 1;
			$r = translate('C_TIPS_SUCCESS_TEXT');
		} else {
			$r = translate('C_TIPS_ERROR_TEXT');
		}
		json_output($c, $r);

	}

	function multi() {
		
		 $type = $this->input->post("type");
		 $ids = $this->input->post("ids");
		 $c = 0;
		 $r = '';
		 if (count(explode(',', $ids)) == 0) 
		 {
		 	$r = translate('C_INVALID_PARAMS');
		 } else 
		 {
			 if ($type == 'delete') 
			 {
			 	//提取tableenum与strategyid出来
			 	
			 	$idArray = explode(',', $ids);
			 	foreach ($idArray as  $value)
			 	{
				 	$strArr = explode("-", $value);
					if (2>count($strArr)) {
						//error(translate('C_INVALID_PARAM_ID', $value));
						print_r($strArr);
						continue;
					}	
					$tableenum = $strArr[0];
					$strategyid = $strArr[1];
					$tablename = $this->moduleList[$tableenum]['tablename'];
					
					$this->db->delete($tablename, array('strategyid' => $strategyid));
			 	}
			 	//$this->db->query("DELETE FROM {pre}role WHERE id IN ({$ids})");
			 	$c = 1;
			 } else 
			 {
			 	$r = translate('C_INVALID_PARAMS');
			 }
		 }
		 json_output($c, $r);
		 
	}

	//根据模块名得到相应的页面
	function getDisplayView($tablename)
	{
		$disaplyView = "";
		switch ($tablename) {
			case "act_mod_wishpond":	//许愿池
				$disaplyView = "editWishpond";
				break;
			case "act_mod_treasurebox":	//地精
				$disaplyView = "editTreasurebox";
				break;
			case "act_mod_fb_card_switch":	//副本翻牌
				$disaplyView = "editFbcardSwitch";
				break;
			case "act_mod_buy_tired":	//购买疲劳值
				$disaplyView = "editBuyTired";
				break;
			case "act_mod_wishwell": //点金
				$disaplyView = "editWishWell";
				break;
			case "act_mod_intensifyattr";	//属性强化
			$disaplyView = "editIntensifyattr";
			break;
			case "act_mod_topfight":	//决斗之颠
				$disaplyView = "editTopFight";
				break;
			case "act_mod_aelafuer":	//守卫拉夫尔
				$disaplyView = "editAelafuer";
				break;
			case "act_mod_angelbless":	//圣魂
				$disaplyView = "editAngelBless";
				break;
			case "act_mod_gangskill":	//公会技能
				$disaplyView = "editGangSkillId";
				break;
			case "act_mod_ladder":	//竞技场
				$disaplyView = "editLadder";
				break;
			case "act_mod_bossfight":	//boss战
				$disaplyView = "editBossFight";
				break;
			case "act_mod_deadtower":	//死亡之塔
				$disaplyView = "editDeadtower";
				break;
			case "act_mod_nomalfb":	//普通副本
				$disaplyView = "editNomalfb";
				break;
			case "act_mod_elite":	//精英副本
				$disaplyView = "editElite";
				break;
			case "act_mod_devils":	//魔王副本
				$disaplyView = "editDeivls";
				break;
			case "act_mod_honorshop":	//魔王副本
				$disaplyView = "editHonorshop";
				break;
			default:
				;
				break;
		}
		return $disaplyView;
	}

}